import { uploadCourse } from '@/services/courseApi';
import { request } from '@umijs/max';
import { useRequest } from 'ahooks';
import { Upload, message, Button } from 'antd';
import { useState } from 'react';

interface UploadProps {
    headers?: { [key: string]: string };
    onUploadSuccess?: (file: any) => void;
    onUploadError?: (file: any) => void;
}

const ExcelFileUpload: React.FC<UploadProps> = ({ headers, onUploadSuccess, onUploadError }) => {
    const [fileList, setFileList] = useState<any[]>([]);

    // const requestRoleList = useRequest(roleListServices, {
    //     manual: true,
    //     loadingDelay: 500,
    //     onSuccess: (res) => {
    //         console.log("res >>> ", res);
    //         // 数据转换
    //         res = res.map((item: any) => { return { value: item.id, label: item.name } })
    //         message.success('获取成功');
    //         setListRoleData(res)
    //     }
    // });

    const handleUploadSubmit = useRequest(uploadCourse, {
        manual: true,
        onSuccess: (data: any) => {
            onUploadSuccess?.(data)
        },
        onError: (error) => {
            message.error('handleUploadSubmit,上传失败');
            console.log(error);
            
            onUploadError?.(error);
        }
    })

    const handleUploadChange = (info: any) => {
        if (info.file.status !== 'uploading') {
            console.log(info.file, info.fileList);
        }
        if (info.file.status === 'done') {
            message.success(`${info.file.name} file uploaded successfully`);
            setFileList(info.fileList);
        } else if (info.file.status === 'error') {
            message.error(`${info.file.name} file upload failed.`);
            onUploadError?.(info.file);
        }
    };

    const customUploadAction = async (options: any) => {
        const { file } = options;
        const formData = new FormData();
        formData.append('excelFile', file);

        try {
            handleUploadSubmit.run(formData);
        } catch (error) {
            message.error('文件上传失败');
        }
    };

    const uploadProps = {
        name: 'excelFile',
        headers,
        onChange: handleUploadChange,
        customRequest:customUploadAction
    };
    return (
        <Upload
            showUploadList={false}
            {...uploadProps}>
            <Button type="primary">上传新课表</Button>
        </Upload>
    );
};

export default ExcelFileUpload;